package com.example.experiment_2java.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.experiment_2java.annotation.Role;
import com.example.experiment_2java.annotation.RoleAuthorization;
import com.example.experiment_2java.entity.Inventory;
import com.example.experiment_2java.entity.ReadBook;
import com.example.experiment_2java.persistence.InventoryMapper;
import com.example.experiment_2java.persistence.ReadBookMapper;
import com.example.experiment_2java.util.result.DataResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/book")
public class BorrowController {
    @Autowired
    private ReadBookMapper readBookMapper;
    @Autowired
    private InventoryMapper inventoryMapper;

    @GetMapping("/loan")
    public DataResult bookLoan(@RequestParam(value = "barcode",required = false) String barcode,
                               @RequestParam(value = "isbn", required = false) String isbn) {
        // barcode不为空，根据isbn是否为空查询
        // 若isbn不为空，则barcode和isbn要匹配
        QueryWrapper<ReadBook> queryWrapper = new QueryWrapper<>();
        if (barcode != null && !barcode.isEmpty()) {
            queryWrapper.eq("barcode", barcode);
            List<ReadBook> readBooks = readBookMapper.selectList(queryWrapper);
            if (isbn != null && !isbn.isEmpty()) {
                Inventory inventory = inventoryMapper.selectById(barcode);
                if (inventory != null && inventory.getIsbn().equals(isbn)) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("loan", readBooks);
                    map.put("inventory", inventory);
                    return DataResult.successByDatas(map).setApiLink("/api");
                }
                return DataResult.err().setApiLink("/api");
            }
            return DataResult.successByDataArray(readBooks).setApiLink("/api");
        }
        // barcode为空，根据isbn查询是否被借阅过
        if (isbn != null && !isbn.isEmpty()) {
            // 查询isbn包含的所有barcode
            QueryWrapper<Inventory> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("isbn", isbn);
            List<Inventory> inventories = inventoryMapper.selectList(queryWrapper2);
            HashMap<String, Object> map = new HashMap<>();
            // 存储有借阅记录的两个列表
            List<ReadBook> readBooks = new ArrayList<>();
            List<Inventory> inventories2 = new ArrayList<>();
            // 遍历isbn包含的barcode，查阅是否有借阅记录
            if (inventories != null && !inventories.isEmpty()) {
                inventories.forEach(inventory -> {
                    String barcode2 = inventory.getBarcode();
                    Map<String, Object> map2 = new HashMap<>();
                    map2.put("barcode", barcode2);
                    List<ReadBook> readBooks1 = readBookMapper.selectByMap(map2);
                    if (readBooks1 != null && !readBooks1.isEmpty()) {
                        ReadBook first = readBooks1.getFirst();
                        readBooks.add(first);
                        inventories2.add(inventory);
                    }
                });
                if (!readBooks.isEmpty()) {
                    map.put("loan", readBooks);
                    map.put("inventory", inventories2);
                    return DataResult.successByDatas(map).setApiLink("/api");
                }
                return DataResult.err().setApiLink("/api");
            }
        }
        return DataResult.err().setApiLink("/api");
    }

    /**
     * 新增书籍借阅信息
     *
     * @param readBook
     * @return
     */
    @PostMapping("/loan")
    public DataResult addLoan(@RequestBody ReadBook readBook) {
        if (readBookMapper.insert(readBook) > 0) {
            return DataResult.successByMessage("新增借阅记录成功", null).setApiLink("/api");
        } else {
            return DataResult.err().setApiLink("/api");
        }
    }


    /**
     * 更新书籍借阅信息
     *
     * @param readBook
     * @return
     */
    @PutMapping("/loan")
    public DataResult updateLoan(@RequestBody ReadBook readBook) {
        if (readBook.getId() == 0) {
            return DataResult.err().setApiLink("/api");
        }
        if (readBookMapper.updateById(readBook) > 0) {
            return DataResult.successByMessage("更新借阅信息成功", null).setApiLink("/api");
        } else {
            return DataResult.err().setApiLink("/api");
        }
    }

    /**
     * 删除书籍借阅信息
     * 仅管理员可使用
     *
     * @param id
     * @return
     */
    @DeleteMapping("/loan")
    @RoleAuthorization(Role.MANAGER)
    public DataResult deleteLoan(@RequestParam int id) {
        if (readBookMapper.deleteById(id) > 0) {
            return DataResult.successByMessage("删除借阅信息成功", null).setApiLink("/api");
        } else {
            return DataResult.err().setApiLink("/api");
        }
    }
}
